package com.zty.shiro;

import com.zty.entity.Permissions;
import com.zty.entity.Role;
import com.zty.entity.User;
import com.zty.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 *
 * 自定义Realm用于查询用户的角色和权限信息并保存到权限管理器
 * @author tyzhang
 * @Date: 2021/1/19 14:25
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    LoginService loginService;

    /** 授权 */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取登录用户名
        String userName = (String) principals.getPrimaryPrincipal();
        // 查询用户名称
        User user = loginService.getUserByName(userName);
        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()){
            // 添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            for (Permissions permissions : role.getPermissions()){
                // 添加权限
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /** 认证 */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        String username1 = token1.getUsername();
//        String username = token.getPrincipal().toString();
        User user = loginService.getUserByName(username1);
        if (user == null){
            return  null;
        }else {
            // 返回认证信息
            return new SimpleAuthenticationInfo(username1, user.getPassword(), getName());
        }

    }
}
